package com.gopay.bis.njcb.ebank.operation;


import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.njcb.ebank.NjcbB2cMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.ICertHelper;
import com.koalii.svs.SvsSign;
import com.koalii.svs.SvsVerify;

public class NjcbB2cCertHelper implements ICertHelper {

	private final static String splistFlag = "||";
	public String sign(BaseMessage bsaeMessage) throws GopayException {
		NjcbB2cMessage message = (NjcbB2cMessage) bsaeMessage;
		SvsSign signer = new SvsSign();
		try {
			BankLogUtils.printB2CSignPlainLog(message);
			signer.initSignCertAndKey(message.getPrivateKeyPath(), message.getPrivatePwd());			
			String szRet = signer.signData(message.getPlainMessage().getBytes("gb2312"));			
			String szCert = signer.getEncodedSignCert();
			BankLogUtils.printB2CSignSignatureLog(message, szRet);
			return szRet + splistFlag + szCert;
		} catch (Exception e) {
			BankLogUtils.printB2CSignExceptionLog(message, e);
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6029);
		}
	}

	public Object verify(BaseMessage bsaeMessage) throws GopayException {
		NjcbB2cMessage message = (NjcbB2cMessage) bsaeMessage;		
		int nRet;
		try {
			BankLogUtils.printB2CVerifyPlainLog(message);
			BankLogUtils.printB2CVerifySignatureLog(message,message.getSignMessage());
			nRet = SvsVerify.verify(message.getPlainMessage().getBytes("GBK"),message.getSignMessage(), message.getPublicKeyPath());
			boolean isVerify = nRet == 0 ? true : false;
			BankLogUtils.printB2CVerifyResultLog(message, isVerify);
			return isVerify;
		} catch (Exception e) {
			BankLogUtils.printB2CSignExceptionLog(message, e);
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6031);
		}

	}

}
